package com.bw.demoseckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.demoseckill.entity.TbUser;
import com.bw.demoseckill.mapper.UserMapper;
import com.bw.demoseckill.service.UserService;
import com.bw.demoseckill.utils.JwtTokenUtils;
import com.bw.demoseckill.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseResult doUserLogin(String userName, String userPwd) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();
        //查询工作人员
        TbUser user = userMapper.selectOne(new QueryWrapper<TbUser>()
                .eq("user_name",userName));
        //用户不存在
        if(user == null) {
            result.setSuccess(false);
            result.setMessage("工作人员不存在");
            return result;
        }

        //判断密码
        String password = userPwd + "." +user.getUserSalt();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!user.getUserPwd().equals(md5Password)){
            result.setSuccess(false);
            result.setMessage("用户密码不正确");
            return result;
        }

        //生成token
        String token = JwtTokenUtils.makeToken(user.getId(), user.getUserName(), "user");
        resultMap.put("user", user);
        resultMap.put("token", token);
        result.setResult(resultMap);
        return result;
    }
}
